#pragma once

#include <iostream>
#include <string>
#include <fstream>
#include <unordered_map>
#include "Logger.hpp"

static const std::string sep = ": ";

class Dictionary
{
private:
    void LoadConf()
    {
        //打开文件
        std::ifstream in(_path);
        if(!in.is_open())
        {
            LOG(LogLevel::ERROR) << "open error!";
            return ;
        }
        //走到这里说明打开文件成功，搜素需要查询的英文
        std::string line;
        while(std::getline(in, line))
        {
            auto pos = line.find(sep);
            if(pos == std::string::npos)
            {
                //没有找到
                LOG(LogLevel::WARNING) << "format error!" ;
                continue;
            }
            //找到了,分割字符串
            std::string word = line.substr(0, pos);
            std::string value = line.substr(pos + sep.size());
            //若为空
            if(word.empty() || value.empty())
            {
                LOG(LogLevel::WARNING) << "format error, word empty or value empty!";
                continue;
            }
            //说明找到需要查询的字母
            _dict.insert(std::make_pair(word, value));
        }
        //关闭文件
        in.close();
    }
public:
    Dictionary(const std::string &path)
        :_path(path)
    {
        LoadConf();
    }
    std::string Translate(const std::string &word, const std::string &whoip, uint16_t whoport)
    {
        (void)whoip;
        (void)whoport;
        auto iter = _dict.find(word);
        if(iter == _dict.end())
        {
            return "unknown";
        }
        return (iter->first + "->" + iter->second);
    }
    ~Dictionary()
    {}
private:
    std::string _path;
    std::unordered_map<std::string,std::string> _dict;
};